package com.ssextjs.data;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SqlReader extends DataReader{
	private String[] fields=null;
	public SqlReader() {
		System.err.println("SqlReader loaded.");
	}
	
	public SqlReader(String[] cols) {
		fields = cols;
		System.err.println("SqlReader loaded.");
	}
	
	public List read(ResultSet rs) {
		ArrayList res = new ArrayList();
		try {
			String[] cnames;
			if (fields!=null) {
				cnames = fields;
			}else{
				ResultSetMetaData rsmd = rs.getMetaData();
				cnames = new String[rsmd.getColumnCount()];
				for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    cnames[i - 1] = rsmd.getColumnName(i);
                }
			}
			while (rs.next()) {
				Map row = new HashMap();
				for (int i=0; i<cnames.length; i++) {
					Object val = rs.getObject(cnames[i]);
					row.put(cnames[i], val);
				}
				res.add(row);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.err.println("SqlReader read records from ResultSet. COUNT: "+res.size());
		return res;	
	}
}
